package cn.com.se.sharepictrue.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.com.se.sharepictrue.R;
import cn.com.se.sharepictrue.adapter.ShareListAdapter;
import cn.com.se.sharepictrue.bean.HomeShareBean;
import cn.com.se.sharepictrue.business.CallBack;
import cn.com.se.sharepictrue.business.NetworkResponse;
import cn.com.se.sharepictrue.business.ShareApi;
import cn.com.se.sharepictrue.quickadapter.BaseAdapterHelper;
import cn.com.se.sharepictrue.utils.StringUtils;
import cn.com.se.sharepictrue.utils.ToastUtils;

/**
 * 搜索界面
 * Created by KIDNG on 2015/12/8.
 */
public class SearchActivity extends AppCompatActivity implements SwipeRefreshLayout.OnRefreshListener, ShareListAdapter.ShareItemStatusListener {
    private static final int REQUEST_CODE_SEARCH = 2;
    @Bind(R.id.tb_concern_title)
    Toolbar mTbConcernTitle;
    @Bind(R.id.ll_search_list)
    ListView mLlSearchList;
    @Bind(R.id.srl_search_refresh)
    SwipeRefreshLayout mSrlSearchRefresh;
    private SearchView searchView;
    private int nowPage;
    private String search;
    private List<HomeShareBean> mSearchList;
    private ShareListAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initToolbar();
        getIntentData();
        initRefreshView();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            search = intent.getStringExtra("search");
        }
    }

    private void initToolbar() {
        setSupportActionBar(mTbConcernTitle);
    }

    private void initRefreshView() {
        mSrlSearchRefresh.setOnRefreshListener(this);
        mSrlSearchRefresh.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mSrlSearchRefresh.post(new Runnable() {
            @Override
            public void run() {
                mSrlSearchRefresh.setRefreshing(true);
                initData();
            }
        });
    }

    private void initData() {
        if (StringUtils.isEmpty(search)) return;
        mLlSearchList.setEnabled(false);
        ShareApi.search(this, search, new CallBack<NetworkResponse<List<HomeShareBean>>>() {
            @Override
            public void onStart() {
                super.onStart();
                mSrlSearchRefresh.setRefreshing(true);
            }

            @Override
            public void onFail() {
                mSrlSearchRefresh.setRefreshing(false);
                mLlSearchList.setEnabled(true);
                ToastUtils.show(SearchActivity.this, "加载失败..");
            }

            @Override
            public void onResponse(NetworkResponse<List<HomeShareBean>> response) {
                mSrlSearchRefresh.setRefreshing(false);
                mLlSearchList.setEnabled(true);
                if (!response.isStatus()) {//加载失败
                    ToastUtils.show(SearchActivity.this, response.getError());
                } else {
                    mSearchList = response.getData();
                    initList();
                }
            }
        });
    }

    private void initList() {
        if (mSearchList != null && mSearchList.size() > 0) {
            mAdapter = new ShareListAdapter(this, R.layout.item_share_list, mSearchList);
            mAdapter.setShareItemStatusListener(this);
            mLlSearchList.setAdapter(mAdapter);
            mLlSearchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Intent intent = new Intent(SearchActivity.this, ShareDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("key", mAdapter.getItem(position));
                    intent.putExtra("item", bundle);
                    intent.putExtra("position", position);
                    startActivityForResult(intent, REQUEST_CODE_SEARCH);
                }
            });
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search_search);//在菜单中找到对应控件的item
        searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        initSearchView(menuItem);
        return true;
    }

    private void initSearchView(MenuItem menuItem) {
        MenuItemCompat.setOnActionExpandListener(menuItem, new MenuItemCompat.OnActionExpandListener() {//设置打开关闭动作监听
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                return true;
            }

            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                return true;
            }
        });
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(SearchActivity.this, query, Toast.LENGTH_LONG).show();
                if (!StringUtils.isEmpty(query)) {
                    search = query;
                    doSearch();
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                return true;
            }
        });
    }

    private void doSearch() {
        initData();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onRefresh() {
        initData();
    }

    @Override
    public void avatarClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(SearchActivity.this, PersonalHomepageActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", item);
        intent.putExtra("key", bundle);
        startActivity(intent);
    }

    @Override
    public void concernClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String concernId = item.getConcernUserId();
        if (concernId == null) ToastUtils.show(SearchActivity.this, "请登录");
        else
            ShareApi.concern(SearchActivity.this, item.getUserId(),
                    concernId.equals(HomeShareBean.HOME_SHARE_NO_CONCERN),
                    new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(SearchActivity.this, "操作失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(SearchActivity.this, response.getError());
                    else {
                        if (item.getConcernUserId().equals(HomeShareBean.HOME_SHARE_NO_CONCERN))
                            item.setConcernUserId(item.getUserId());
                        else
                            item.setConcernUserId(HomeShareBean.HOME_SHARE_NO_CONCERN);
                        mAdapter.notifyDataSetChanged();
                    }

                }
            });

    }

    @Override
    public void praiseClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String likeIt = item.getPraiseStatus();
        if (likeIt == null) ToastUtils.show(SearchActivity.this, "请登录");
        else if (likeIt.equals(HomeShareBean.HOME_SHARE_NO_PRAISE)) {
            ShareApi.praise(SearchActivity.this, item.getShareId(), 1, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(SearchActivity.this, "点赞" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus()) {
                        ToastUtils.show(SearchActivity.this, response.getError());
                    } else {
                        item.setPraiseStatus(HomeShareBean.HOME_SHARE_IS_PRAISE);
                        item.setPraiseNum(item.getPraiseNum() + 1);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        } else if (likeIt.equals(HomeShareBean.HOME_SHARE_IS_PRAISE)) {
            ShareApi.praise(SearchActivity.this, item.getShareId(), 0, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(SearchActivity.this, "点赞" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus()) {
                        ToastUtils.show(SearchActivity.this, response.getError());
                    } else {
                        item.setPraiseStatus(HomeShareBean.HOME_SHARE_NO_PRAISE);
                        item.setPraiseNum(item.getPraiseNum() - 1);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    @Override
    public void collectionClick(BaseAdapterHelper helper, final HomeShareBean item) {
        String favorite = item.getFavoriteStatus();
        if (favorite == null) ToastUtils.show(SearchActivity.this, "请登录");
        else if (favorite.equals(HomeShareBean.HOME_SHARE_NO_FAVORITE)) {
            ShareApi.favorite(SearchActivity.this, item.getShareId(), 1, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(SearchActivity.this, "收藏" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(SearchActivity.this, response.getError());
                    else {
                        item.setFavoriteStatus(HomeShareBean.HOME_SHARE_IS_FAVORITE);
                        mAdapter.notifyDataSetChanged();
                    }

                }
            });
        } else {
            ShareApi.favorite(SearchActivity.this, item.getShareId(), 0, new CallBack<NetworkResponse<String>>() {
                @Override
                public void onFail() {
                    ToastUtils.show(SearchActivity.this, "取消收藏" + item.getUserName() + "失败");
                }

                @Override
                public void onResponse(NetworkResponse<String> response) {
                    if (!response.isStatus())
                        ToastUtils.show(SearchActivity.this, response.getError());
                    else {
                        item.setFavoriteStatus(HomeShareBean.HOME_SHARE_NO_FAVORITE);
                        mAdapter.notifyDataSetChanged();
                    }
                }
            });
        }
    }

    @Override
    public void commentClick(BaseAdapterHelper helper, HomeShareBean item) {
        Intent intent = new Intent(SearchActivity.this, ShareDetailActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("key", item);
        intent.putExtra("item", bundle);
        intent.putExtra("position", helper.getPosition());
        startActivityForResult(intent, REQUEST_CODE_SEARCH);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        HomeShareBean item = null;
        int position = -1;
        if (requestCode == REQUEST_CODE_SEARCH && resultCode == Activity.RESULT_OK) {
            Log.d("xxxxxxxxxxxxxx", "return ok");
            if (data != null) {
                Bundle bundle = data.getBundleExtra("item");
                if (bundle != null)
                    item = (HomeShareBean) bundle.getSerializable("key");
                position = data.getIntExtra("position", -1);
            }
            if (item != null) Log.d("sssssss", item.toString());
            if (item != null && position != -1 && mAdapter.getCount() > position) {
                mAdapter.set(position, item);
            }
        }
    }
}
